<?php
namespace app\admin\controller;
use think\facade\Db;
use app\admin\model\{Question as QuestionModel,Option,Answer,User};
use hg\apidoc\annotation as Apidoc;
use app\common\BaseController;
use think\Request;


/**
 * @Apidoc\Title("答题管理")
 **/
class Question extends BaseController{
    

    /**
     * @Apidoc\Title("列表")
     * @Apidoc\Url("user/index")
     * @Apidoc\Method("GET")
     * @Apidoc\Tag("account")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("start",type="int",desc="起始位置"),
     *   @Apidoc\Returned("limit",type="int",desc="查询数量"),
     *   @Apidoc\Returned("data",type="array",desc="返回数据"),
     *   @Apidoc\Returned("total",type="array",desc="数据总量")
     * )
     */
    public function index(Request $request){
        $page  = (int)$request->param('page', 0);
        $limit  = (int)$request->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        if(isset($search['title']) && $search['title'] !=''){
            $wheres[] = ['title','like',"%{$search['title']}%"];
        }
        $query  = QuestionModel::where($wheres);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

        /**
     * 批量导入
     * @return void
     * @author Sam
     */
    public function import(){
        if(empty($_FILES['file'])) json_response(0, '请选择文件');
        $list = big_csv_to_array($_FILES['file']['tmp_name']);
        set_time_limit(0);
        try{
            $num = 0;
            if(count($list)){
                foreach($list as $k=>$value){
                    if(!empty($value[0])) {
                        Db::startTrans();
                        try {
                            $question =  QuestionModel::create([
                                 'title' => trim((string)$value[0]),
                                 'remark' => trim((string)$value[7]),
                                 'right_answer' => trim((string)$value[6])
                             ]);
                             $insert_data = ['A'=>$value[1],'B'=>$value[2],'C'=>$value[3],'D'=>$value[4],'E'=>$value[5]];
                             foreach($insert_data as $k=>$v){
                                 if(trim($v) != '' && $v){
                                      $option =  Option::create([
                                         'question_id' => $question->id,
                                         'option_name' => $v,
                                         'option_number'  => $k 
                                     ]);
                                 }
                                 if($k == trim((string)$value[6])){
                                     $question->answer_id = $option->id;
                                     $question->save();
                                 }
                             }
                             $num += 1;
                            Db::commit();
                         } catch (\Exception $e) {
                            Db::rollback();
                            $num = 0;
                            json_response(0,$e->getMessage());
                         }
                       
                    }
                }
            }
                return  $this->success('导入成功'.$num.'条数据');
            }catch(\Exception $e){
                return $this->error($e->getMessage());
            }
    }

    /**
     * 答题记录
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public function record(){
        $page  = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        if(isset($search['question']) && $search['question'] !=''){
            $ids = QuestionModel::where('title','like',"%{$search['question']}%")->column('id');
            if($ids && is_array($ids)){
                $wheres[] = ['question_id','in',$ids];
            } 
        }
        if(isset($search['user']) && $search['user'] !=''){
            $ids = User::where('mobile|name','like',"%{$search['user']}%")->column('id');
            if($ids && is_array($ids)){
                $wheres[] = ['uid','in',$ids];
            } 
        }
        if(isset($search['is_right']) && $search['is_right'] !=''){
            $wheres[] = ['is_right','=',$search['is_right']];
        }
        $query  = Answer::with(['question','user'])->where($wheres);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

    /**
     * 下载模板
     *
     * @return void
     * @Description
     * @example
     * @author Sam
     * @since 
     */
    public function down_temp(){
      header("Location:https://game.vrupup.com/resources/sam_base/answer.csv");
      exit();
    }



   /**
    * 添加题目
    * @return void
    * @author Sam
    * @date 2022-04-27
    */
    public function create(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'option' => 'require',
                'title' => 'require',
                'right_answer' => 'require',
            ], [
               'option.require'  => '选项不得为空',
               'title.require'      => '名称必须',
               'right_answer.require'      => '答案不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        if(count($data['option']) < 2){
            json_response(0,'选项不得少于1个');
        }
        foreach ($data['option'] as $key => $value) {
            if(trim($value['option_number']) == '' || trim($value['option_name']) == ''){
                json_response(0,'请完善选项');
            }
            if(\in_array(trim($value['option_number']),['A','B','C','D','E']) == false){
                json_response(0,'选项必须为A,B,C,D,E等勿加空格');
            }
        }
        $right_answer_arr   = explode(',',$data['right_answer']); //正确答案数组
        $option_number_arr  = array_column($data['option'],'option_number'); //选项编号数组
        foreach ($right_answer_arr as $v) {
            if(!in_array($v,$option_number_arr)){
                json_response(0,'该答案在选项中不存在');
            }
        }
        if(QuestionModel::where('title',$data['title'])->count()){
            json_response(0,'该题目已存在');
        }
        Db::startTrans();
            try {
               $question =  QuestionModel::create([
                    'title'        => $data['title'],
                    'remark'       => $data['remark'],
                    'right_answer' => $data['right_answer'],
                    'pic'          => $data['pic'] ?? ''
                ]);
                if($data['option']){
                    foreach ($data['option'] as $key => $value) {
                       $Option =  Option::create([
                            'question_id' => $question->id,
                            'option_name' => $value['option_name'],
                            'option_number' => $value['option_number']
                        ]);
                        if($value['option_number'] == $data['right_answer']){
                            $question->answer_id = $Option->id;
                            $question->save();
                        }
                    }
                }
               Db::commit();
            } catch (\Exception $e) {
               Db::rollback();
               json_response(0,$e->getMessage());
            }
            json_response(1,'添加成功');
        }
    
    /**
     * 题目详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-04-27
     */
 public function detail(int $id): \think\response\Json
        {
            try {
                $row  = QuestionModel::where('id', $id)->append(['option'])->find();
            } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
                return $this->error($e->getMessage());
            }
    
            return $this->success('', $row);
        }

        /**
     * 删除选项
     * @return void
     * @author Sam
     * date 2021-02-26
     */
    public function del_option(){
            $id       = request()->post('id/d');
            if($option = Option::where(['id'=>$id])->find()){
                if($option->delete()){
                    json_response(1,'删除成功');
                }else{
                    json_response(0,'删除失败');
                }
            }else{
                json_response(0,'无此选项记录');
            }
    }

    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function edit(){
           $data = request()->post();
           try {
               $this->validate($data, [
                   'id'    => 'require',
                   'option' => 'require',
                   'title' => 'require',
                   'right_answer' => 'require',
               ], [
                   'id.require'  => 'id不得为空',
                  'option.require'  => '选项不得为空',
                  'title.require'      => '名称必须',
                  'right_answer.require'      => '答案不得为空',
               ]);
           } catch (\Exception $e) {
               json_response(0,$e->getError());
           }
           if(count($data['option']) < 2){
               json_response(0,'选项不得少于1个');
           }
           foreach ($data['option'] as $key => $value) {
               if(trim($value['option_number']) == '' || trim($value['option_name']) == ''){
                   json_response(0,'请完善选项');
               }
               if(\in_array(trim($value['option_number']),['A','B','C','D','E']) == false){
                   json_response(0,'选项必须为A,B,C,D,E等勿加空格');
               }
           }
           $right_answer_arr   = explode(',',$data['right_answer']); //正确答案数组
           $option_number_arr  = array_column($data['option'],'option_number'); //选项编号数组
           foreach ($right_answer_arr as $v) {
               if(!in_array($v,$option_number_arr)){
                   json_response(0,'该答案在选项中不存在');
               }
           }
           if(QuestionModel::where('title',$data['title'])->where('id','<>',$data['id'])->count()){
               json_response(0,'该题目已存在');
           }
           $question = QuestionModel::find($data['id']);
           unset($data['create_time']);
            Db::startTrans();
            try {
                $question->save($data);
                if($data['option']){
                    foreach ($data['option'] as $key => $value) {
                        if($option = Option::where('question_id',$data['id'])->where('option_number',$value['option_number'])->find()){
                            $option->option_name = $value['option_name'];
                            $option->option_number = $value['option_number'];
                            $option->save();
                        }else{
                            Option::create([
                                'question_id' => $question->id,
                                'option_name' => $value['option_name'],
                                'option_number' => $value['option_number']
                            ]);
                        }
                    }
                }
               Db::commit();
            } catch (\Exception $e) {
               Db::rollback();
               json_response(0,$e->getMessage());
            }
            return json_response(1,'编辑成功');
        
    }


        
    
    /**
     * 导出excell
     * @return void
     * @author Sam
     *
     */
    public function question_export(){
        $search = request()->param();
        $wheres = [];
        if(isset($search['question']) && $search['question'] !=''){
            $ids = QuestionModel::where('title','like',"%{$search['question']}%")->column('id');
            if($ids && is_array($ids)){
                $wheres[] = ['question_id','in',$ids];
            } 
        }
        if(isset($search['user']) && $search['user'] !=''){
            $ids = User::where('mobile|name','like',"%{$search['user']}%")->column('id');
            if($ids && is_array($ids)){
                $wheres[] = ['uid','in',$ids];
            } 
        }
        if(isset($search['is_right']) && $search['is_right'] !=''){
            $wheres[] = ['is_right','=',$search['is_right']];
        }
        $query  = Answer::with(['question','user'])->where($wheres);
        big_array_to_csv($query,'text.csv',[
            'id'=>'ID',
            'nickname'=>'昵称',
            'mobile'=>'手机号',
            'question'=>['题目',function($row){
                return $row['question']['title'];
            }],
            'is_right' => ['是否正确',function($row){
                if($row['is_right'] == 1){
                    return '正确';
                }elseif($row['is_right'] == 2){
                    return '部分正确';
                }elseif($row['is_right'] ==3){
                    return '跳过';
                }else{
                    return '错误';
                }
            }],
            'create_time'=>'答题时间',
        ]);
        
    }


        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function delete(){
        $id = param_check('ids');
        if(!$QuestionModel = QuestionModel::where('id','in',$id)->select()) json_response(0,'不存在');
        if($QuestionModel->delete()) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }

}